﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using MvcSample.Data.Core;
using MvcSample.Models;

namespace MvcSample.Controllers
{
    public class AccountController : Controller
    {
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly UserManager<ApplicationUser> _userManager;
        public AccountController(SignInManager<ApplicationUser> signInManager,
            UserManager<ApplicationUser> userManager)
        {
            _signInManager = signInManager;
            _userManager = userManager;
        }

        public IActionResult SignIn()
        {
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> SignIn([FromForm]SignInVm signInVm)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(signInVm.UserName);
                if (user == null)
                {
                    return RedirectToAction(nameof(SignUp));
                }
                var rt = await _signInManager.PasswordSignInAsync(signInVm.UserName, signInVm.Password, true, false);
                if (rt.Succeeded)
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View(signInVm);
        }
        public IActionResult SignUp()
        {
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> SignUp(SignUpVm signUpVm)
        {
            var rt = await _userManager.CreateAsync(new ApplicationUser() { UserName = signUpVm.UserName }, signUpVm.Password);
            if (rt.Succeeded)
            {
                await _signInManager.PasswordSignInAsync(signUpVm.UserName, signUpVm.Password, true, false);
                return RedirectToAction("Index", "Home");
            }
            return View(signUpVm);
        }

        public async Task<IActionResult> SignOutAsync()
        {
            await _signInManager.SignOutAsync();
            return RedirectToAction("index", "home");
        }
    }
}